<template>
  <el-container style="height: 100%">
    <el-header height="60px">
      <div style="margin-top: 10px">
        <el-button type="primary" @click="group_and_prepare">合并需求</el-button>
      </div>
      <el-divider></el-divider>
    </el-header>
    <el-main>
      <el-table :data="tableData" stripe height="100%">
        <el-table-column
          v-for="column in tableColumns"
          :key="column.code"
          :prop="column.code"
          :label="column.name"
          :width="column.width ? column.width : 100"
          :formatter="
            (row, column, cellValue, index) => {
              return cell_formatter(column, cellValue, tableColumns)
            }
          "
        />
        <el-table-column label="操作" :width="120">
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              v-if="scope.row.optimize === 1"
              @click="scope.row.optimize = 0"
              >算料</el-button
            >
            <el-button size="small" v-if="scope.row.optimize === 0" @click="scope.row.optimize = 1"
              >取余料</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-main>
  </el-container>
</template>

<script lang="ts" setup>
import { divide_demand_define } from '@/meta/index'
import type { divide_demand } from '@/types/billdata'
import { fill_ref_info, cell_formatter } from '@/utils/common'
import { onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { e_optimize } from '@/types/enum'
import { groupDivideBills } from '@/utils/groupUtils'
import { useDbStore } from '@/stores/modules/database'
const dbStore = useDbStore()
const tableColumns = divide_demand_define
const router = useRouter()
const tableData = ref<divide_demand[]>()
const group_and_prepare = () => {
  const divide_demands_prepare = tableData.value?.filter((r) => r.optimize === e_optimize.算料)
  dbStore.saveDivideDemand(divide_demands_prepare!)
  const divide_demand_sum = groupDivideBills(divide_demands_prepare!)
  fill_ref_info(divide_demand_sum, divide_demand_define)
  dbStore.saveDivideDemandSum(divide_demand_sum)
  router.push({ path: '/divideDemandSum' })
}
onMounted(() => {
  const tmp = dbStore.dividedemandbill
  fill_ref_info(tmp, divide_demand_define)
    .then(() => {
      tableData.value = tmp
    })
    .catch(() => {
      console.log('err')
    })
})
</script>
